package com.xexun.gpstracker;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.*;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.amap.api.location.AMapLocation;
import com.lurencun.service.autoupdate.AppUpdate;
import com.lurencun.service.autoupdate.AppUpdateService;
import com.xexun.gpstracker.baby.BabyFragmentAMAP;
import com.xexun.gpstracker.baby.BabyFragmentGMAP;
import com.xexun.gpstracker.baby.activity.ChatActivity;
import com.xexun.gpstracker.babygroup.BabyGroupFragment;
import com.xexun.gpstracker.badgenumberlibrary.BadgeNumberManager;
import com.xexun.gpstracker.badgenumberlibrary.BadgeNumberManagerXiaoMi;
import com.xexun.gpstracker.badgenumberlibrary.MobileBrand;
import com.xexun.gpstracker.base.BaseActivity;
import com.xexun.gpstracker.base.GTFragment;
import com.xexun.gpstracker.channel.R;
import com.xexun.gpstracker.common.*;
import com.xexun.gpstracker.dialog.VibrateDialog;
import com.xexun.gpstracker.fix.grant.PermissionsManager;
import com.xexun.gpstracker.fix.grant.PermissionsResultAction;
import com.xexun.gpstracker.found.FoundFragment;
import com.xexun.gpstracker.inter.*;
import com.xexun.gpstracker.msg.MsgMainFragment;
import com.xexun.gpstracker.my.MyFragment;
import com.xexun.gpstracker.pojo.*;
import com.xexun.gpstracker.service.CommunicationService;
import com.xexun.gpstracker.indoorlocation.IndoorFragment;
import com.xexun.gpstracker.study.StudyFragment;
import com.xexun.gpstracker.study.TakePhotoActivity;
import com.xexun.gpstracker.ui.BackHandlerFragment;
import com.xexun.gpstracker.util.*;
import com.xexun.gpstracker.view.BadgeView;
import com.xexun.gpstracker.vo.*;
import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.Subscriber;
import org.xutils.common.Callback;
import org.xutils.common.util.KeyValue;
import org.xutils.db.sqlite.SqlInfo;
import org.xutils.db.table.DbModel;
import org.xutils.ex.DbException;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * APP主页面
 *
 * @author huangfei
 */
public class MainActivity extends BaseActivity implements BackHandledInterface {

    private String TAG = MainActivity.class.getSimpleName();

    private GTFragment mBabyFragment;
    private BabyGroupFragment mBabyGroupFragment;
    private FoundFragment mFoundFragment;
    private MyFragment mMyFragment;
    private MsgMainFragment msgMainFragment;
    private StudyFragment mStudyFragment;
    private IndoorFragment mIndoorFragment;
    private Fragment mCurrentFragment;
    FragmentManager fragmentManager;
    private LinearLayout babyGroupLayout, nearbyLayout, myLayout, babyLayout, msgLayout, studyLayout, atdLayout, bottomLayout;
    private ImageView babyIV, babyGroupIV, nearbyIV, myIV, msgIV, studyIV, atdIV;
    private TextView babyTextView, babyGroupTextView, nearbyTextView, myTextView, msgTextView, studyTextView, atdTextView;
    private BackHandlerFragment mBackHandlerFragment;

    public static List<String> mEmoticons = new ArrayList<String>();
    public static Map<String, Integer> mEmoticonsId = new HashMap<String, Integer>();
    public static List<String> mEmoticons_Zemoji = new ArrayList<String>();
    public static List<String> mEmoticons_Zgif = new ArrayList<String>();
    private BadgeView badge;
    private BadgeView badgeMSG;
    public static Map<String, Integer> unreadData = new HashMap<>();  //未读信息的条数记录
    public int unReadCount = 0;    //未读消息的总数量
    private SharedPreferences mSharedPreferences;
    private static MainActivity activity;
    private long currentBackPressedTime = 0;  //点击返回键的时间
    private static final int BACK_PRESSED_INTERVAL = 2000;  //退出的时间间隔
    // 定位相关
    private LocationProvider locationProvider;

    private String currImei;
    private String position;

    public static MainActivity getActivity() {
        return activity;
    }



    /**
     * 用户登录
     *
     */
    private void login() {
//        final String savedPhone = mSharedPreferences.getString(MyConstants.USER_PHONE, "");
//        String pwd = mSharedPreferences.getString(MyConstants.USER_PWD, "");

        User.login(this, "22222222", "123456", new HttpCallback() {
            @Override
            public void onStart() {
            }

            @Override
            public void onFinish() {
            }

            @Override
            public void onSuccess(ResponseData obj) {
                Log.i(TAG, obj.getMsg());
                if (obj.getRetcode() == 1) {
                    //Session.getInstance().setAccessKey(JSONHelper.getString(obj.getBody(), "accesskey"));
                    Session.getInstance().setAccessKey(JSONHelper.getString(obj.getBody(), "accesskey"));
                    User user = new User();
                    user.setId(JSONHelper.getLong(obj.getBody(), "id"));
                    user.setPhone("22222222");
                    user.setAppUserNum(JSONHelper.getString(obj.getBody(), "appUserNum"));
                    user.setImei(obj.getBodyString("imei"));
                    Session.getInstance().setUser(user);
                    Session.getInstance().setImei(user.getImei());

                    AppContext.termType = JSONHelper.getInt(obj.getBody(), "type");

                    AppContext.isEntered = true;

                }
            }

            @Override
            public void onFailure(String message) {
            }
        });
    }




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_main);



        activity = MainActivity.this;
        mSharedPreferences = Utils.getPreferences(activity);



        //登录
//        login();

        if(Session.getInstance().getClientId() == null) {//当程序崩溃时重启此activity时此条件满足
            finish();
            return;
        }


        //注册事件总线
        AppContext.getEventBus().register(this);

        initView();
        fragmentManager = getFragmentManager();

        Session.getInstance().setRegistedImei(getIntent().getStringExtra("imei"));
        Session.getInstance().setValidCode(getIntent().getStringExtra("validCode"));

        if(!isMyServiceRunning()) {
            Intent serviceIntent = new Intent(this, CommunicationService.class);
            startService(serviceIntent);
        }

        loadingEmoji();
        checkNewVersion();
//        checkEmoticonVersion();
        Constants.loctionInterval = mSharedPreferences.getInt(MyConstants.LOCATION_INTERVAL_TIME, Constants.defaultInterval);
        Log.i(Constants.TAG, "登录后定位");
        getLocationEx();

        /**
         * 程序首次运行初始化一个碎片
         */
        mBabyFragment = getBabyFragment();
        //mBabyFragment = IndoorFragment.newInstance();

        if (mCurrentFragment != null) {
            switchFragment(mCurrentFragment, mBabyFragment);
        } else {
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.fragment_place, mBabyFragment).commit();
        }
        mCurrentFragment = mBabyFragment;

        checkNewMeaasge();

        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(this,
                new String[]{Constants.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
                new PermissionsResultAction() {
                    @Override
                    public void onGranted() {
                        mBabyFragment.initView();
                    }

                    @Override
                    public void onDenied(String permission) {
                        CommUtil.showMsgLong(String.format(getString(R.string.permission_refuse_comm_note), getString(R.string.permission_refuse_map_note)));
                        AppManager.getAppManager().finishActivity(MainActivity.this);
                        logout(false);
                    }
                });
    }

    /**
     * 获取最新版本
     */

    static final String UPDATEURL = Constants.baseUrl+"terminal/update";


    /**
     * 加载程序自带表情数据
     */
    private void loadingEmoji() {
        /**
         * 表情暂时使用的是png静态图，如果以后添加其他类型的图片，需要进行判断文件类型，然后将类型参数也对应添加到集合
         */
//        for (int i = 1; i < 59; i++) {
//            String emoticonsName = "[zemoji" + i + ".png]";
//            int emoticonsId = getResources().getIdentifier("zemoji_e" + i,
//                    "drawable", getPackageName());
//            mEmoticons.add(emoticonsName);
//            mEmoticons_Zemoji.add(emoticonsName);
//            mEmoticonsId.put(emoticonsName, emoticonsId);
//        }
        //加载APP自带表情
        for (int i = 1; i < 100; i++) {
            String num;
            if (i < 10) {
                num = "0" + i;
            } else {
                num = Integer.valueOf(i).toString();
            }
            String emoticonsName = "[zgif" + num + ".gif]";
            int emoticonsId = getResources().getIdentifier("zgif" + num, "drawable", getPackageName());
            if (emoticonsId == 0) {
                break;
            }
            mEmoticons.add(emoticonsName);
            mEmoticons_Zgif.add(emoticonsName);
            mEmoticonsId.put(emoticonsName, emoticonsId);
        }

        String ZgifName = Utils.listToString(mEmoticons_Zgif);
        //保存表情数据到SP中
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putString(MyConstants.EMOJI_APP_OLD, ZgifName);
        editor.apply();
    }

    /**
     * 检查是否有新的图片需要更新,如果不更新，则使用drawable内的表情，如果更新，则优先使用新表情
     */
    private void checkEmoticonVersion() {
        int emotIconLocalVersion = mSharedPreferences.getInt(MyConstants.EMOTI_VERSION, 12);//初始版本号为12
        try {
            JSONObject data = new JSONObject();
            data.put("version", emotIconLocalVersion);
            HttpCallback callback = new HttpCallback() {
                @Override
                public void onStart() {

                }

                @Override
                public void onFinish() {

                }

                @SuppressLint("StringFormatInvalid")
                @Override
                public void onSuccess(ResponseData obj) throws Exception {
                    if (obj.getRetcode() == 1) {
                        JSONObject jsonObject = obj.getBody();
                        final int emotIconNetVersion = JSONHelper.getInt(jsonObject, "version");
                        boolean downloadState = JSONHelper.getState(jsonObject, "downloadState");
                        if (downloadState) {
                            //需要更新，获得新版本的下载链接
                            final String newEmotIconVersionUrl = obj.getMsg();
                            final Dialog dialog = new Dialog(activity, R.style.dialog);
                            dialog.setContentView(R.layout.dialog_found_emoji);
//                            dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

                            TextView title = (TextView) dialog.findViewById(R.id.title);
                            TextView feature = (TextView) dialog.findViewById(R.id.feature);
                            title.setText(String.format(MainActivity.this.getResources().getString(R.string.latest_version_title),getString(R.string.emoji_package)));
                            feature.setText(R.string.new_emoji_downloader);
                            View ignore = dialog.findViewById(R.id.ignore);
                            View update = dialog.findViewById(R.id.update);
                            ignore.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    //忽略
                                    dialog.dismiss();
                                }
                            });
                            update.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    dialog.dismiss();
                                    File filesDir = new File(activity.getFilesDir() + "/emoji/gif/");
                                    if (!filesDir.exists()) {
                                        //不存在，则创建文件目录
                                        filesDir.mkdirs();
                                    } else {
                                        //删除原files/emoji/gif目录下的文件
                                        File[] listFile = filesDir.listFiles();
                                        if (listFile != null) {
                                            for (File mFile : listFile) {
                                                if (!mFile.isDirectory()) {
                                                    mFile.delete();
                                                }
                                            }
                                        }
                                    }
                                    //下载文件
                                    DownLoaderTask downloaderTask = new DownLoaderTask(newEmotIconVersionUrl, activity.getFilesDir() + "/emoji/", activity.getFilesDir() + "/emoji/gif/", activity, emotIconNetVersion);
                                    downloaderTask.execute();
//                                  downloaderTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                                }
                            });
                            dialog.setCancelable(false);
                            dialog.getWindow().setGravity(Gravity.CENTER);
                            dialog.show();

                        }
                    }
                }

                @Override
                public void onFailure(String message) throws Exception {
                    Toast.makeText(activity, R.string.new_emoji_downloader_err, Toast.LENGTH_SHORT).show();
                }
            };
            //使用异步请求链接对象
            HttpUtil.post(CommonRestPath.AppEmoticonVersion(), data, new JsonHttpResponseHelper(callback).getHandler());
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /**
     * 检查是否存在未读信息
     */
    public void checkNewMeaasge() {

        unreadData.clear();
        unReadCount = 0;
        Log.d(TAG, "未读数据总数标记");
        //获取数据库数据
        try {
            //查询未读消息的个数以及对应的IMEI
//          SqlInfo sqlInfo = new SqlInfo("select imei,count(is_read) unRead from chat_msg where is_read=? and user_id=? group by imei");

            List<Device> devices = Session.getInstance().getMonitors();

            if(devices.size() == 0 ){
                return;
            }

            for (Device device : devices){
                SqlInfo sqlInfo = new SqlInfo("select imei,count(is_read) unRead from chat_msg where is_read=? and imei=? and user_id=? group by imei");
                sqlInfo.addBindArg(new KeyValue("is_read", 0));
                sqlInfo.addBindArg(new KeyValue("imei", device.getImei()));
                sqlInfo.addBindArg(new KeyValue("user_id", Session.getInstance().getLoginedUserId()));
//                sqlInfo.addBindArg(new KeyValue("user_id", Session.getInstance().getLoginedUserId()));
                List<DbModel> dbModels = AppContext.db.findDbModelAll(sqlInfo);

                Log.d(TAG, "MainActivity 未读数据总数标记：（1或以上代表有未读数据，0代表没有）：" + dbModels.size());

                for (DbModel dbModel : dbModels) {
                    HashMap<String, String> dataMap = dbModel.getDataMap();
                    int unRead = Integer.parseInt(dataMap.get("unRead"));
                    unReadCount += unRead;
                    String imei = dataMap.get("imei");
                    unreadData.put(imei, unRead);
                }
            }

            Log.d(TAG,"未读消息条数："+unReadCount);

            //清除旧提示
            if (unReadCount != 0) {
                badgeMSG.setText(Integer.valueOf(unReadCount).toString());
                badgeMSG.setVisibility(View.VISIBLE);
                if (!Build.MANUFACTURER.equalsIgnoreCase(MobileBrand.XIAOMI)) {
                    BadgeNumberManager.from(MainActivity.this).setBadgeNumber(unReadCount);
                    Log.d(TAG,"非小米手机");
//                    Toast.makeText(MainActivity.this, "设置桌面角标成功", Toast.LENGTH_SHORT).show();
                }

            } else {
                badgeMSG.setVisibility(View.GONE);
                if (!Build.MANUFACTURER.equalsIgnoreCase(MobileBrand.XIAOMI)) {
                    Log.d(TAG,"小米手机");
                    BadgeNumberManager.from(MainActivity.this).setBadgeNumber(0);
                }

            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    //订阅收到消息，进行通讯
    @Subscriber(tag = Constants.EVENT_TAG_UNREAD_DATA)
    private synchronized void displayMsg(ChatMsg chatMsg) {
        String imei = chatMsg.getImei();
        Integer ct = unreadData.get(imei);
        if (ct != null) {
            unreadData.put(imei, ++ct);
        } else {
            unreadData.put(imei, 1);
        }

        checkNewMeaasge();
//        badgeMSG.setText(Integer.valueOf(++unReadCount).toString());
//        badgeMSG.setVisibility(View.VISIBLE);
//        badgeMSG.invalidate();
        AppContext.getEventBus().post(chatMsg, Constants.EVENT_TAG_UNREAD_DATA_AFTER);
    }

    protected void onResume() {
        super.onResume();
        VibrateDialog.getInstance().bleDisconnected(MainActivity.this);
        if (Session.getInstance().getMainActivity() == null) {
            Session.getInstance().setMainActivity(MainActivity.this);
        }
        int flag = Session.getInstance().getiFlag();
        if (flag == 1) {
            Intent intent = new Intent();
            intent.setClass(MainActivity.this, ChatActivity.class);
            intent.putExtra("chat", Session.getInstance().getMapEntity());
            startActivity(intent);
            Session.getInstance().setiFlag(0);
        }

        if (!Constants.hasNewVersion) {
            if (null != badge) {
                badge.setVisibility(View.GONE);
                badge = null;
            }
        }

        if (CommUtil.isNotBlank(currImei) && CommUtil.isNotBlank(position)) {
            switchToBabyFragment(currImei, position);
            currImei = null;
            position = null;
        }

        //查询是否存在未读数据
        checkNewMeaasge();
        //getLocation();
    }

    protected void onDestroy() {
        // 退出时销毁定位
        if (locationProvider != null) {
            locationProvider.stop();
        }
        AppContext.getEventBus().unregister(this);
        super.onDestroy();
    }

    private void checkNewVersion() {
        if (Constants.hasNewVersion) {
            badge = new BadgeView(MainActivity.this);
            badge.setTargetView(myIV);
            badge.showAsDot();
        }
    }

    private void getLocation() {
        locationProvider =  LocationProviderAMAP.getInstance(this);

//        locationProvider = Constants.IS_CHINA_VERSION ? LocationProviderAMAP.getInstance(this) : LocationProviderGMAP.getInstance(this);
        locationProvider.startLocation(new NotifyCallback() {
            @Override
            public void execute(GTLatLng location) {
                Session.getInstance().setLatLng(location);
//                Session.getInstance().setGsmCellInfo(Utils.getGSMCellLocationInfo(MainActivity.this));
//                Session.getInstance().setWifiInfo(Utils.getWifiInfo(MainActivity.this));
                //上传ＧＰＳ
                //User.postGPS();
            }
        });
    }

    public static void getLocationEx() {
        Log.i(Constants.TAG, "开始定位");
        LocationProvider locProvider = LocationProviderAMAP.getInstance(AppContext.getContext()) ;

//        LocationProvider locProvider = Constants.IS_CHINA_VERSION ? LocationProviderAMAP.getInstance(AppContext.getContext()) : LocationProviderGMAP.getInstance(AppContext.getContext());
        locProvider.startLocation(new NotifyCallbackEx() {
            @Override
            public void execute(Location loc) {
                GTLatLng latLng = new GTLatLng(loc.getLatitude(), loc.getLongitude());
                Session.getInstance().setLatLng(latLng);
                Session.getInstance().setAMAPLoc(loc);
                sendLocationMsg();
//                Session.getInstance().setGsmCellInfo(Utils.getGSMCellLocationInfo(MainActivity.this));
//                Session.getInstance().setWifiInfo(Utils.getWifiInfo(MainActivity.this));
                //上传ＧＰＳ
                //User.postGPS();
            }
        });
    }

    private static void sendLocationMsg() {
        Log.i(Constants.TAG, "发送定位数据");
        try {
            JSONObject data = new JSONObject();
            data.put("imei", Session.getInstance().getClientId());

            SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
            String time = fmt.format(new Date());
            data.put("time", time);

            GTLatLng latLng = Session.getInstance().getLatLng();
            data.put("latitude", latLng.getLatitude() + "");
            data.put("longitude", latLng.getLongitude() + "");

            Location loc = Session.getInstance().getLoc();
            data.put("type", ((AMapLocation) loc).getLocationType());

//            if (Constants.IS_CHINA_VERSION) {
//                data.put("type", ((AMapLocation) loc).getLocationType());
//            } else {
//                data.put("type", 1);
//            }
            String JSONStr = data.toString();

            ChatMsg chatMsg = new ChatMsg();
            chatMsg.setIsSend(true);
            chatMsg.setId(-1L);
            chatMsg.setImei(Session.getInstance().getClientId());
            chatMsg.setType(ContType.JSON.getType());
            chatMsg.setTermType(TermType.APP.getType().intValue());//(Entity.getTermType().getType());
            chatMsg.setContent(JSONStr);
            chatMsg.setUserId(Session.getInstance().getLoginedUserId());
            chatMsg.setTime(System.currentTimeMillis());
            //MessageSender.getInstance(activity).sendMessage(chatMsg);
            AppContext.getEventBus().post(chatMsg, Constants.EVENT_TAG_CHAT_SEND);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化一些控件
     */
    private void initView() {
        babyGroupLayout = (LinearLayout) findViewById(R.id.babyGroupLayout);
        nearbyLayout = (LinearLayout) findViewById(R.id.nearbyLayout);
        myLayout = (LinearLayout) findViewById(R.id.myLayout);
        babyLayout = (LinearLayout) findViewById(R.id.babyLayout);
        msgLayout = (LinearLayout) findViewById(R.id.msgLayout);
        studyLayout = (LinearLayout) findViewById(R.id.studyLayout);
        atdLayout = (LinearLayout) findViewById(R.id.attendanceLayout);

        babyIV = (ImageView) findViewById(R.id.babyIV);
        babyGroupIV = (ImageView) findViewById(R.id.babyGroupIV);
        nearbyIV = (ImageView) findViewById(R.id.nearbyIV);
        myIV = (ImageView) findViewById(R.id.myIV);
        msgIV = (ImageView) findViewById(R.id.msgIV);
        studyIV = (ImageView) findViewById(R.id.studyIV);
        atdIV = (ImageView) findViewById(R.id.attendanceIV);

        babyTextView = (TextView) findViewById(R.id.babyTV);
        babyGroupTextView = (TextView) findViewById(R.id.babyGroupTV);
        nearbyTextView = (TextView) findViewById(R.id.nearbyTV);
        myTextView = (TextView) findViewById(R.id.myTV);
        msgTextView = (TextView) findViewById(R.id.msgTV);
        studyTextView = (TextView) findViewById(R.id.studyTV);
        atdTextView = (TextView) findViewById(R.id.attendanceTV);
        badgeMSG = (BadgeView) findViewById(R.id.badgeMSG);

        babyLayout.setOnClickListener(clickListener);
        babyGroupLayout.setOnClickListener(clickListener);
        nearbyLayout.setOnClickListener(clickListener);
        myLayout.setOnClickListener(clickListener);
        msgLayout.setOnClickListener(clickListener);
        studyLayout.setOnClickListener(clickListener);
        atdLayout.setOnClickListener(clickListener);

    /*    bottomLayout = (LinearLayout)findViewById(R.id.bottomLayout);
        bottomLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                bottomLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);

                bottomLayout.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                int height =  bottomLayout.getMeasuredHeight(); //底部菜单的高度
            }
        });*/
    }

    /**
     * 底部菜单选择事件
     */
    private OnClickListener clickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            clearFocus();
            switch (v.getId()) {
                case R.id.babyLayout:
                    switchToBabyFragment(null, null);
                    break;
                case R.id.babyGroupLayout:
                    babyGroupIV.setBackgroundResource(R.drawable.baby_group_checked);
                    babyGroupTextView.setTextColor(getResources().getColor(R.color.bar_color_focus));
                    if (mBabyGroupFragment == null) mBabyGroupFragment = BabyGroupFragment.newInstance();
                    switchFragment(mCurrentFragment, mBabyGroupFragment);
                    mBabyFragment.closeTimer();
                    break;
                case R.id.nearbyLayout:
                    nearbyIV.setBackgroundResource(R.drawable.nearby_checked);
                    nearbyTextView.setTextColor(getResources().getColor(R.color.bar_color_focus));
                    if (mFoundFragment == null) mFoundFragment = FoundFragment.newInstance();
                    switchFragment(mCurrentFragment, mFoundFragment);
                    mBabyFragment.closeTimer();
                    break;
                case R.id.myLayout:
                    myIV.setBackgroundResource(R.drawable.setting_checked);
                    myTextView.setTextColor(getResources().getColor(R.color.bar_color_focus));
                    if (mMyFragment == null) mMyFragment = MyFragment.newInstance();
                    switchFragment(mCurrentFragment, mMyFragment);
                    mBabyFragment.closeTimer();
                    break;
                case R.id.msgLayout:
                    msgIV.setBackgroundResource(R.drawable.msg_checked);
                    msgTextView.setTextColor(getResources().getColor(R.color.bar_color_focus));
                    if (msgMainFragment == null) {
                        msgMainFragment = MsgMainFragment.newInstance();
                    }
                    switchFragment(mCurrentFragment, msgMainFragment);
                    mBabyFragment.closeTimer();
                    break;

                case R.id.studyLayout:
                    studyIV.setBackgroundResource(R.drawable.study_checked);
                    studyTextView.setTextColor(getResources().getColor(R.color.bar_color_focus));
                    if (mStudyFragment == null) {
                        mStudyFragment = StudyFragment.newInstance();
                    }
                    switchFragment(mCurrentFragment, mStudyFragment);
                    mBabyFragment.closeTimer();
                    break;

                case R.id.attendanceLayout:
                    Intent intent = new Intent();
                    intent.setClass(activity, TakePhotoActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    activity.startActivity(intent);
                    mBabyFragment.closeTimer();
                    break;
            }
        }
    };

    private void switchToBabyFragment(String imei, String position) {
        clearFocus();
        babyIV.setBackgroundResource(R.drawable.baby_checked);
        babyTextView.setTextColor(getResources().getColor(R.color.bar_color_focus));
        if (mBabyFragment == null) {
            mBabyFragment = getBabyFragment();
            //mBabyFragment = IndoorFragment.newInstance();
        }
        mBabyFragment.setCurrImei(imei);
        mBabyFragment.setPosition(position);
        switchFragment(mCurrentFragment, mBabyFragment);
    }

    private GTFragment getBabyFragment() {
        return Constants.IS_CHINA_VERSION ? BabyFragmentAMAP.newInstance() : BabyFragmentGMAP.newInstance();
//        return BabyFragmentAMAP.newInstance();
    }

    public void switchFragment(Fragment from, Fragment to) {
        if (from.equals(to)) return;
        if (to == null) return;
        FragmentTransaction transaction = this.fragmentManager.beginTransaction();
        if (!to.isAdded()) {
            // 隐藏当前的fragment，add下一个到Activity中
            transaction.hide(from).add(R.id.fragment_place, to).commit();
        } else {
            // 隐藏当前的fragment，显示下一个
            transaction.hide(from).show(to).commit();
        }
        this.mCurrentFragment = to;
    }

    /**
     * 清除所有的选中按钮
     */
    private void clearFocus() {
        babyIV.setBackgroundResource(R.drawable.baby_uncheck);
        babyGroupIV.setBackgroundResource(R.drawable.baby_group_uncheck);
        nearbyIV.setBackgroundResource(R.drawable.nearby_unckecked);
        myIV.setBackgroundResource(R.drawable.setting_unchecked);
        msgIV.setBackgroundResource(R.drawable.msg_unckecked);
        studyIV.setBackgroundResource(R.drawable.study_unchecked);

        TextView[] textViews = new TextView[]{babyTextView, babyGroupTextView, nearbyTextView, myTextView, msgTextView, studyTextView};
        for (TextView tv : textViews) {
            tv.setTextColor(getResources().getColor(R.color.bar_color_unfocus));
        }
        //清除可能存在的定位状态
        closeRealtimeLocation();
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
//            logoutDialog();
//            return false;
//        }
//        return false;
//    }


    /**
     * 应用退出
     */
    protected void logoutDialog() {
        AlertDialog.Builder builder = new Builder(MainActivity.this);
        builder.setMessage(R.string.confirm_logout_txt);
        builder.setTitle(R.string.msg_notify);
        builder.setCancelable(false);
        builder.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                logout(false);
                AppContext.isEntered = false;
                dialogInterface.dismiss();

            }
        });
        builder.setNegativeButton(R.string.cancel, null);
        builder.create().show();
    }

    @Override
    public void setSelectedFragment(BackHandlerFragment selectedFragment) {
        this.mBackHandlerFragment = selectedFragment;
    }

    @Override
    public void onBackPressed() {
        //以后如果其他Fragment界面需要响应返回键，请将Fragment继承BackHandlerFragment,实现onBackPressed方法即可，可参考BabyFragment.java
        if (!mBackHandlerFragment.onBackPressed()) {
            closeRealtimeLocation();
        } else {
            // logoutDialog();
            //按两次返回键，隐藏当前应用
            if (System.currentTimeMillis() - currentBackPressedTime > BACK_PRESSED_INTERVAL) {
                currentBackPressedTime = System.currentTimeMillis();
                Toast.makeText(this, R.string.back_login_out_prompt, Toast.LENGTH_SHORT).show();
            } else {
                //虚假退出
//                Intent startMain = new Intent(Intent.ACTION_MAIN);
//                startMain.addCategory(Intent.CATEGORY_HOME);
//                startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(startMain);
//                if (unReadCount > 0){
//                    if (Build.MANUFACTURER.equalsIgnoreCase(MobileBrand.XIAOMI)) {
//                        new Handler().postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                setXiaomiBadgeNumber(unReadCount);
//                            }
//                        },3000);
//                        Log.i(TAG, "设置退出后台，未读条数为："+unReadCount);
//                    }
//                }


                moveTaskToBack(true);
            }
        }
    }


    /**
     * 清除定位状态
     */
    public void closeRealtimeLocation() {
        if (mBackHandlerFragment != null) {
            mBackHandlerFragment.onBackPressed();
        }
    }

    @Subscriber(tag = Constants.EVENT_TAG_REFRESH_POSITION)
    private void refreshPosition(ChatMsg chatMsg) {
        currImei = chatMsg.getImei();
        position = chatMsg.getOriginalContent();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }

    private boolean isMyServiceRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if ("com.xexun.gpstracker.service.CommunicationService".equals(service.service.getClassName())) {
                Log.i(Constants.TAG, "服务已存在");
                return true;
            }
        }
        Log.i(Constants.TAG, "服务不存在");
        return false;
    }
}
